package com.example.app2024.infosave;

import android.Manifest;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.annotation.ReturnThis;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.example.app2024.R;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class infosaveActivity extends AppCompatActivity
{
      EditText editText1;
      Button btn_sharedsave, btn_sharedread;
      Button btn_leibusave, btn_leiburead;
      private static final int REQUEST_PERMISSION = 1;
      private static final String[] PERMISSIONS = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};

      @Override
      protected void onCreate(Bundle savedInstanceState)
      {
            super.onCreate(savedInstanceState);
            EdgeToEdge.enable(this);
            setContentView(R.layout.activity_infosave);
            ViewCompat.setOnApplyWindowInsetsListener(
                    findViewById(R.id.main), (v, insets) -> {
                          Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
                          v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
                          return insets;
                    });
            editText1 = findViewById(R.id.shared_et);
            btn_sharedsave = findViewById(R.id.btn_sharedsave);
            btn_sharedread = findViewById(R.id.btn_sharedread);
            btn_leibusave = findViewById(R.id.btn_leibusave);
            btn_leiburead = findViewById(R.id.btn_leiburead);


            sharedPerferences();


            内部存储();

      }

      // 请求权限
      private void requestPermission()
      {
            ActivityCompat.requestPermissions(this, PERMISSIONS, REQUEST_PERMISSION);
      }

      void 内部存储()
      {
            if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED) )
            {
                  Toast.makeText(infosaveActivity.this, "SDcard不存在", Toast.LENGTH_SHORT).show();
                  return;
            }
            requestPermission();

            int result = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
            if (result != PackageManager.PERMISSION_GRANTED)
            {
                  Toast.makeText(infosaveActivity.this, "文件权限被拒绝了,退出", Toast.LENGTH_SHORT).show();
                  return;
            } else
            {
                  Toast.makeText(infosaveActivity.this, "文件权限通过", Toast.LENGTH_SHORT).show();
            }

            String path = this.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS) + "/zxj.txt";

            btn_leibusave.setOnClickListener(new View.OnClickListener()
            {
                  @Override
                  public void onClick(View v)
                  {
                        File file = new File(path);
                        try
                        {
                              if (!file.exists())
                              {
                                    file.createNewFile();
                                    Toast.makeText(infosaveActivity.this, "文件将创建", Toast.LENGTH_SHORT).show();
                              } else
                              {
                                    Toast.makeText(infosaveActivity.this, "文件已存在", Toast.LENGTH_SHORT).show();
                              }
                              FileOutputStream fos = new FileOutputStream(path, false);
                              fos.write(editText1.getText().toString().getBytes());
                              Toast.makeText(infosaveActivity.this, "保存外部文件成功", Toast.LENGTH_SHORT).show();
                        } catch (Exception e)
                        {
                              Log.i("TAG", e.toString());
                              //throw new RuntimeException(e);
                        }
                  }
            });

            btn_leiburead.setOnClickListener(new View.OnClickListener()
            {
                  @Override
                  public void onClick(View v)
                  {
                        FileInputStream fileInputStream = null;
                        try
                        {
                              fileInputStream = new FileInputStream(path);
                        } catch (FileNotFoundException e)
                        {
                              throw new RuntimeException(e);
                        }
                        byte[] bytes = new byte[1024];
                        int len = 0;
                        try
                        {
                              len = fileInputStream.read(bytes);
                        } catch (IOException e)
                        {
                              throw new RuntimeException(e);
                        }
                        String string = new String(bytes, 0 , len);
                        Toast.makeText(infosaveActivity.this, "外部读取的是:"+string, Toast.LENGTH_SHORT).show();
                  }
            });


      }

      void sharedPerferences()
      {
            btn_sharedsave.setOnClickListener(new View.OnClickListener()
            {
                  @Override
                  public void onClick(View v)
                  {
                        String userName = editText1.getText().toString().trim();

                        SharedPreferences preferences = infosaveActivity.this.getSharedPreferences("myshared", MODE_PRIVATE);
                        SharedPreferences.Editor editor = preferences.edit();
                        editor.putString("username", userName);
                        editor.commit();
                        Toast.makeText(infosaveActivity.this, "已保存", Toast.LENGTH_SHORT).show();
                  }
            });

            btn_sharedread.setOnClickListener(new View.OnClickListener()
            {
                  @Override
                  public void onClick(View v)
                  {
                        SharedPreferences preferences = infosaveActivity.this.getSharedPreferences("myshared", MODE_PRIVATE);
                        String userName = preferences.getString("username", "null");
                        Toast.makeText(infosaveActivity.this, "您上次保存的用记名为" + userName, Toast.LENGTH_SHORT).show();
                  }
            });
      }
}